package chabernac.gravidroid.model;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class GravitySimulator {
	private static final float TIMESTEP = 0.01F;

	private final List<iMass> myMasses = new CopyOnWriteArrayList<iMass>();

	private final List<Mass> myInternalMasses = new CopyOnWriteArrayList<Mass>();

	public synchronized void addMass(iMass aMass) {
		myMasses.add(aMass);
		myInternalMasses.addAll(aMass.getInteralMasses());
	}

	public synchronized void removeMass(Mass aMass) {
		myMasses.remove(aMass);
		myInternalMasses.removeAll(aMass.getInteralMasses());
	}

	public synchronized List<iMass> getMasses() {
		return myMasses;
	}

	public synchronized List<Mass> getInternalMasses() {
		return myInternalMasses;
	}

	public void iterate() {
		for (Mass theMass : myInternalMasses)
			theMass.resetForce();

		for (iMass theMass : myMasses) {
			theMass.resetCollisions();
			theMass.calculateInternalForces();
		}

		int i = 0;
		while (i < myMasses.size()) {
			iMass theMass = myMasses.get(i);
			for (int j = i + 1; j < myMasses.size(); j++) {
				iMass theOtherMass = myMasses.get(j);
				theMass.calculateForce(theOtherMass);
			}
			i++;
		}

		for (Mass theMass : myInternalMasses) {
			theMass.calculateAcceleration();
			theMass.calculateNewLocation(TIMESTEP);
		}
	}

	public void removeMasses(List<Mass> theMasses) {
		myMasses.removeAll(theMasses);
	}

}
